import { Component,ChangeDetectorRef  } from '@angular/core';
import { NavController, NavParams,AlertController,ActionSheetController } from 'ionic-angular';
import { DataService } from '../../app/core/data/DataService';
import { BaseService } from '../../app/core/data/BaseService';
import { SecurityService } from '../../app/core/security/SecurityService';
import { LoginPage } from '../login/login';
import { BpmObject } from '../../app/bpm/BpmObject';
import { LoadingController } from 'ionic-angular';
import { BpmBackPage } from '../../pages/bpmback/bpmback';
import { BpmSignPage } from '../../pages/bpmsign/bpmsign';
import { BpmProcessPage } from '../../pages/bpmprocess/bpmprocess';
import { BpmImgPage } from '../../pages/bpmimg/bpmimg';
import { FileTransferObject } from '@ionic-native/file-transfer';
import {Camera} from "@ionic-native/camera"; 


@Component({
  selector: 'page-wjry',
  templateUrl: 'wjry.html'
})

export class WjryPage {
  readonly="";
  solution="不显示";
  haveError=false;
  user={};

  public gzwjryrqxk:BpmObject=new BpmObject(this.dataService,this.baseSErvice,
    this.changeDetectorRef,this.navCtrl,this.alert,this.loadingCtrl,);
  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    private dataService:DataService,
    private baseSErvice:BaseService,
    private alert:AlertController,
	private securityService:SecurityService,
	public changeDetectorRef:ChangeDetectorRef, 
  public loadingCtrl: LoadingController,
  public actionSheetCtrl: ActionSheetController,

  privateactionSheetCtrl:ActionSheetController,
    private camera:Camera,
    private fileTransfer:FileTransferObject
  
  ) {
	this.gzwjryrqxk.editRow={};
	this.gzwjryrqxk.sn="gzwjryrqxk";
	this.gzwjryrqxk.bpmKey=this.navParams.data["bk"];
	this.gzwjryrqxk.id=this.navParams.data["dk"];

    if(this.securityService.user==null || this.securityService.user["userid"]==null){
      this.securityService.getUserInfo(()=>{
        this.user = this.securityService.user;
		//this.initUserExam();
		this.gzwjryrqxk.findWork("gzwjryrqxk",null,null);
      },()=>{
        this.goLogin();
      })
    }else{
      this.user = this.securityService.user;
	  this.gzwjryrqxk.findWork("gzwjryrqxk",null,null);
    }
  }

  goLogin(){
    this.navCtrl.push(LoginPage);
  };
  backPage(){
    this.navCtrl.pop();
  };

  goSignPage(){
    this.navCtrl.push(BpmSignPage,this.gzwjryrqxk);
  };

  goBackPage(){
    this.navCtrl.push(BpmBackPage,this.gzwjryrqxk);
  };

  goProcessPage(){
    //this.navCtrl.push(BpmProcessPage,this.gzccgl);
    let actionSheet = this.actionSheetCtrl.create({
      title: '更多',
      buttons: [
        {
          text: '办理过程',
          handler: () => {
            //console.log('Destructive clicked');
            this.navCtrl.push(BpmProcessPage,this.gzwjryrqxk);
          }
        },{
          text: '流程图',
          handler: () => {
            this.navCtrl.push(BpmImgPage,this.gzwjryrqxk);
          }
        },{
          text: '取消',
          role: '取消',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  };

  private cameraOpt = {
    quality: 30,
    destinationType: 1, // Camera.DestinationType.FILE_URI,
    sourceType: 1, // Camera.PictureSourceType.CAMERA,
    encodingType: 0, // Camera.EncodingType.JPEG,
    mediaType: 0, // Camera.MediaType.PICTURE,
    allowEdit: false,
    correctOrientation: true,
    saveToPhotoAlbum:true
  };

  // private imagePickerOpt = {
  //   maximumImagesCount: 1,//选择一张图片
  //   width: 800,
  //   height: 800,
  //   quality: 80
  //   };

// 图片上传的的api
public uploadApi:string;

upload: any= {
    url:this.baseSErvice.baseUrl+"/userfile/plupload/appUploadFile",
    fileKey: 'upload',//接收图片时的key
    fileName: 'imageName.jpg',
    headers: {
      'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'//不加入 发生错误！！
    },
    params: {}, //需要额外上传的参数
    success: (data)=> { },//图片上传成功后的回调
    error: (err)=> { },//图片上传失败后的回调
    listen: ()=> { }//监听上传过程
  };

  /**constructor(privateactionSheetCtrl:ActionSheetController,
    private noticeSer:ToastService,
    private camera:Camera,
    private imagePicker:ImagePicker,
    private transfer:FileTransfer,
    private file:File,
    private fileTransfer:FileTransferObject) {
    
    this.fileTransfer= this.transfer.create();
    } */
    
    
    showPicActionSheet(field:string) {
      this.useASComponent(field);
    }

    // 使用ionic中的ActionSheet组件
private useASComponent(field:string) {
  let actionSheet= this.actionSheetCtrl.create(
    {
      title: '请选择',
      buttons: [
        {
        text: '拍照',
        handler: ()=> {
          this.startCamera(field);
        }
      },
      {
      text: '从手机相册选择',
      handler: ()=> {
        this.openImgPicker(field);
        }
      },
      {
        text: '取消',
        role: 'cancel',
        handler: ()=> {
        }
      }
    ]
  });
  actionSheet.present();
  }
  
  // 启动拍照功能
  private startCamera(field:string) {
    this.camera.getPicture(this.cameraOpt).then((imageData)=> {
    this.uploadImg(imageData,field);
  }, (err)=>{
      //this.alert.create({
       // title:"系统提示",
       // subTitle:"无法打开相机，请授权！",
       // buttons:["确定"]
     // }).present();
    });
  }
  
  // 打开手机相册
  private openImgPicker(field:string) {
    /*this.imagePicker.getPictures(this.imagePickerOpt)
      .then((results)=> {
        for (var i=0; i < results.length; i++) {
          temp = results[i];
        }
        this.uploadImg(temp,field);
    }, (err)=> {
      
    });*/

    const options = {
     /* quality: 100,
      //  destinationType: this.camera.DestinationType.FILE_URI,
     // destinationType: this.camera.DestinationType.DATA_URL,
     destinationType: 1,
      encodingType: this.camera.EncodingType.PNG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, 
      correctOrientation:true,
      allowEdit: true,
      targetWidth: 100,
      targetHeight: 100,   */

      quality: 30,
      destinationType: 1, // Camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, // Camera.PictureSourceType.CAMERA,
      encodingType: 0, // Camera.EncodingType.JPEG,
      mediaType: 0, // Camera.MediaType.PICTURE,
      allowEdit: true,
      correctOrientation: true
    }

    this.camera.getPicture(options).then((imageData)=> {
      this.uploadImg(imageData,field);
    }, (err)=>{
     // this.alert.create({
      //  title:"系统提示",
      //  subTitle:"无法打开相册，请授权！",
      //  buttons:["确定"]
     // }).present();
    });
  }
  
  
  // 上传图片
  private uploadImg(path:string,field:string) {
    if (!path) {
      return;
    }

    this.upload.fileName=this.gzwjryrqxk.getGUID()+".jpg";
  
    let options:any;
    options = {
      fileKey: this.upload.fileKey,
      headers: this.upload.headers,
      params: this.upload.params
    };

    let that=this;

    let loader = this.loadingCtrl.create({
        content: "正在上传..."
    });
    loader.present();


    this.fileTransfer.upload(path,this.upload.url, options)
    .then((data)=> {
      loader.dismiss();
      let temp=JSON.parse(data.response);
      that.gzwjryrqxk.editRow[field]=temp["bucket"]+":"+temp["key"]+":"+that.upload.fileName;
      document.getElementById(field).setAttribute("src",this.convertFilePath(that.gzwjryrqxk.editRow[field]));
      that.changeDetectorRef.markForCheck();
      that.changeDetectorRef.detectChanges();
      if (this.upload.success) {
        this.upload.success(JSON.parse(data.response));
      }
  
    }, (err) => {
      loader.dismiss();
      if (this.upload.error) {
      this.upload.error(err);
      } else {
        this.alert.create({
          title:"系统提示",
          subTitle:"抱歉，文件处理异常了，请重试！",
          buttons:["确定"]
        }).present();
      }
    });
  }
  
  // 停止上传
  stopUpload() {
    if (this.fileTransfer) {
      this.fileTransfer.abort();
    }
  };

  convertFilePath=function(fileInfo:string){
    if(fileInfo==null || fileInfo=="") return null;
    let fileInfoArr = fileInfo.split(":");
    if(fileInfoArr.length<3)return null;
    var bucket = fileInfoArr[0];
    var key = fileInfoArr[1];
    var name = fileInfoArr[2];
    var downloadUrl=this.baseSErvice.baseUrl+'/file/plupload/download';
    var _downloadUrl = downloadUrl+"?bucket="+bucket+"&key="+key+"&name="+encodeURIComponent(name);
    return _downloadUrl;
};
}